<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>合同管理</el-breadcrumb-item>
      <el-breadcrumb-item>客户合同</el-breadcrumb-item>
    </el-breadcrumb>

    <Container class="u-mb15">
      <!-- 筛选 -->
      <el-form
        inline
        class="m-form--filter"
      >
        <el-form-item>
          <el-input
            v-model="search.contractNo"
            class="u-w160"
            size="mini"
            clearable
            placeholder="请输入合同编号"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.cooperatorName"
            class="u-w160"
            size="mini"
            filterable
            multiple
            collapse-tags
            placeholder="请选择客户主体"
          >
            <el-option
              v-for="item in contractSubjectOption"
              :key="item.key"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.ownerBody"
            class="u-w160"
            size="mini"
            filterable
            multiple
            collapse-tags
            placeholder="请选择我方主体"
          >
            <el-option
              v-for="item in OUR_PART_OPTION"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.status"
            class="u-w160"
            size="mini"
            multiple
            collapse-tags
            placeholder="请选择合同状态"
          >
            <el-option
              v-for="item in CUSTOMER_STATUS_OPTION"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.suitDepart"
            class="u-w160"
            size="mini"
            placeholder="请选择合同适用部门"
          >
            <el-option
              v-for="item in applicableDeptOption"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="getTable"
            type="primary"
            size="mini"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </Container>

    <Container>
      <!-- 表格操作 -->
      <el-form
        inline
        class="m-table--handle"
      >
        <template v-if="isRole('R010')">
          <el-form-item>
            <el-button
              size="mini"
              @click="toLink('contract-customer-detail', {
              action: 'create',
              origin
            })"
            >新增</el-button>
          </el-form-item>
          <el-form-item>
            <el-upload
              with-credentials
              :action="`${BASE_URL}/cpa/api/contract_new/import`"
              :data="{
                type: contractType
              }"
              :show-file-list="false"
              :on-success="contractUpload"
              :before-upload="contractBeforeUpload"
            >
              <el-button size="mini">导入合同信息</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="contractExport"
              size="mini"
            >导出合同信息</el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              size="small"
              @click="downloadTemplate"
            >下载模板</el-button>
          </el-form-item>
        </template>
        <CustomTableColumn :columns.sync="tableColumn" />
      </el-form>
      <!-- 表格 -->
      <el-table
        border
        stripe
        :data="tableData"
      >
        <el-table-column
          align="center"
          v-for="(item, index) in filterTableColumn"
          :label="item.label"
          :key="index"
          :width="item.width"
          :fixed="item.fixed"
        >
          <template slot-scope="scope">
            <!-- 合同有效期 -->
            <template v-if="item.prop === 'indate'">{{scope.row.startDate + ' ~ ' + scope.row.endDate}}</template>
            <!-- 合同状态 -->
            <template v-else-if="item.prop === 'status'">
              <span :class="{
              'u-red': scope.row.status === 0
            }">{{mapStatus(scope.row.status)}}</span>
            </template>
            <!-- 我方主体 -->
            <template v-else-if="item.prop === 'ownerBody'">{{mapOwnerBody(scope.row.ownerBody)}}</template>
            <!-- 合同适用部门 -->
            <template v-else-if="item.prop === 'suitDepart'">{{mapSuitDepart(scope.row.suitDepart)}}</template>
            <!-- 合同扫描件 -->
            <template v-else-if="item.prop === 'pdfPath'">
              <el-link
                v-if="scope.row.pdfPath"
                type="primary"
                :href="scope.row.pdfPath"
                target="_blank"
              >下载</el-link>
              <el-upload
                v-if="isRole('R010')"
                with-credentials
                :action="`${BASE_URL}/cpa/api/contract_new/upload`"
                :data="{
                  id: scope.row.id
                }"
                :show-file-list="false"
                :on-success="pdfUpload"
                :before-upload="pdfBeforeUpload"
              >
                <el-tooltip
                  effect="dark"
                  content="格式PDF，大小10MB以内"
                  placement="top"
                >
                  <el-button type="text">{{scope.row.pdfPath ? '重新上传' : '上传'}}</el-button>
                </el-tooltip>
              </el-upload>
            </template>
            <!-- 其他 -->
            <template v-else>{{scope.row[item.prop]}}</template>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-button
              v-if="isRole('R010')"
              @click="toLink('contract-customer-detail', {
              action: 'edit',
              origin,
              id: scope.row.id
            })"
              type="text"
            >编辑</el-button>
            <el-button
              @click="toLink('contract-customer-detail', {
              action: 'detail',
              origin,
              id: scope.row.id
            })"
              type="text"
            >查看</el-button>
            <el-button
              v-if="isRole('R010')"
              @click="deleteItem(scope.row.id)"
              type="text"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        :page-sizes="pager.sizes"
        :page-size="pager.limit"
        layout="total, prev, pager, next, sizes"
        :total="pager.total"
        @size-change="handlePagerSizeChange"
        @current-change="handlePagerCurrentChange"
      />
      <!-- 导入提示 -->
      <el-dialog
        title="导入合同信息"
        :visible.sync="importVisible"
      >
        <div
          style="max-height: 400px; overflow: auto; line-height: 28px; margin-top: -20px;"
          v-html="importMessage"
        ></div>
      </el-dialog>
    </Container>
  </div>
</template>

<script>
import Container from "@/components/container";
import CustomTableColumn from "@/components/custom-table-column";

import {
  CUSTOMER_STATUS_OPTION,
  APPLICABLE_DEPT_OPTION,
  OUR_PART_OPTION
} from "@/assets/js/contract-option";
import { isRole } from "@/util";

export default {
  name: "contract-contract-customer",
  components: {
    Container,
    CustomTableColumn
  },
  data() {
    return {
      CUSTOMER_STATUS_OPTION,
      APPLICABLE_DEPT_OPTION,
      OUR_PART_OPTION,

      BASE_URL: process.env.VUE_APP_BASE_URL,

      contractType: 1, // 1客户，2渠道
      contractSubjectOption: [],
      pdfLoading: null,

      importLoading: null,
      importVisible: false,
      importMessage: "",

      search: {
        contractNo: "",
        cooperatorName: [],
        ownerBody: [],
        status: [],
        suitDepart: ""
      },

      pager: {
        sizes: [50, 100, 500],
        limit: 50,
        page: 1,
        total: 0
      },

      tableData: [],
      tableColumn: [
        {
          label: "合同编号",
          prop: "contractNo",
          visible: true,
          fixed: true,
          width: 200
        },
        {
          label: "客户主体",
          prop: "cooperatorName",
          visible: true,
          width: 300
        },
        {
          label: "我方主体",
          prop: "ownerBody",
          visible: true,
          width: 300
        },
        {
          label: "合同有效期（天）",
          prop: "indate", // startDate - endDate
          visible: true,
          width: 210
        },
        {
          label: "合同负责人",
          prop: "shoulder",
          visible: true
        },
        {
          label: "合同状态",
          prop: "status", // 0 即将到期，1 正常，2 未开始，3已过期
          visible: true
        },
        {
          label: "合同适用部门",
          prop: "suitDepart", // 0，信息流 1，商店分发 2，信息流/商店分发
          visible: true
        },
        {
          label: "合同适用平台",
          prop: "suitPlatform",
          visible: true
        },
        {
          label: "合同适用产品",
          prop: "suitProduct",
          visible: true
        },
        {
          label: "推广模式",
          prop: "popMode",
          visible: true
        },
        {
          label: "合同扫描件",
          prop: "pdfPath",
          visible: true
        }
      ]
    };
  },
  computed: {
    filterTableColumn() {
      return this.tableColumn.filter(item => item.visible);
    },
    origin() {
      return this.$route.query;
    },
    requestSearch() {
      return {
        ...this.search,
        type: this.contractType,
        cooperatorName: this.search.cooperatorName.join(),
        ownerBody: this.search.ownerBody.join(),
        status: this.search.status.join(),
        limit: this.pager.limit,
        page: this.pager.page
      };
    },
    applicableDeptOption() {
      // 财务展示：所有选项
      // cpa：商店分发、信息流/商店分发
      // 信息流：信息流、信息流/商店分发
      if (isRole("R010") || isRole("R020")) {
        return APPLICABLE_DEPT_OPTION;
      } else if (isRole("R030")) {
        return APPLICABLE_DEPT_OPTION.filter(
          item => [0, 2].indexOf(item.key) !== -1
        );
      } else {
        return [];
      }
    }
  },
  methods: {
    isRole,
    // 主体下拉
    fetchSubjectOption() {
      this.$http({
        method: "get",
        url: "/cpa/api/contract_new/namelist",
        params: {
          type: this.contractType
        }
      }).then(res => {
        this.contractSubjectOption = res.data.list || [];
      });
    },
    // 获取列表
    getTable() {
      this.$http({
        method: "post",
        url: "/cpa/api/contract_new/query",
        data: this.requestSearch
      }).then(res => {
        this.tableData = res.data.list || [];
        this.pager.total = res.data.total || 0;
      });
    },
    // 对应合同状态
    mapStatus(key) {
      if (typeof key === "undefined") return "";
      return CUSTOMER_STATUS_OPTION.filter(item => Number(item.key) === key)[0]
        .value;
    },
    // 对应我方主体
    mapOwnerBody(key) {
      if (typeof key === "undefined") return "";
      return OUR_PART_OPTION.filter(item => item.key === key)[0].value;
    },
    // 对应合同适用部门
    mapSuitDepart(key) {
      return APPLICABLE_DEPT_OPTION.filter(item => item.key === key)[0].value;
    },
    // pdf上传
    pdfUpload(res) {
      if (res.status === 1) {
        this.getTable();
      } else {
        this.$message({
          type: "error",
          message: res.msg
        });
      }
      this.uploadMessage(res.status === 1);
      this.pdfLoading.close();
    },
    pdfBeforeUpload(file) {
      const type = ["application/pdf"].indexOf(file.type) !== -1;
      const size = file.size / 1024 < 1024 * 10;
      if (!type) {
        this.$message.error("请上传pdf格式的文件");
        return false;
      }
      if (!size) {
        this.$message.error(`文件大小不能超过10MB`);
        return false;
      }
      this.pdfLoading = this.$loading({
        lock: true,
        text: "正在上传...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      return type && size;
    },
    // 导入合同信息
    contractUpload(res) {
      if (res.status === 1) {
        this.importVisible = true;
        this.importMessage = res.msg
          .split(/[：，]/g)
          .map(item => {
            return `<div>${item}</div>`;
          })
          .join("");
      } else {
        this.$message({
          type: "error",
          message: res.msg
        });
      }
      this.importLoading.close();
    },
    contractBeforeUpload(file) {
      const type = /\.xlsx?$/.test(file.name);
      if (!type) {
        this.$message.error("请上传excel格式的文件");
      }
      this.importLoading = this.$loading({
        lock: true,
        text: "正在导入...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      return type;
    },
    // 下载模板
    downloadTemplate() {
      location.href = "/xls/contract-import-template.xls";
    },
    // 导出合同信息
    contractExport() {
      this.$http({
        method: "post",
        url: "/cpa/api/contract_new/export",
        data: this.requestSearch
      }).then(res => {
        if (res.data.status === 1) {
          location = res.data.excelPath;
        }
      });
    },
    // 删除合同
    deleteItem(id) {
      this.$confirm("是否删除此合同数据，删除后不可恢复?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        showClose: false
      })
        .then(() => {
          this.$http({
            method: "delete",
            url: "/cpa/api/contract_new/delete",
            params: {
              id
            }
          }).then(res => {
            if (res.data.status === 1) {
              this.$message({
                type: "success",
                message: "删除成功"
              });
              this.getTable();
            }
          });
        })
        .catch(() => {});
    },
    // 操作提示
    uploadMessage(
      flag,
      success = "上传成功",
      error = "上传失败",
      duration = 3000
    ) {
      if (flag) {
        this.$message({
          duration,
          type: "success",
          showClose: true,
          message: success
        });
      } else {
        this.$message({
          duration,
          type: "error",
          showClose: true,
          message: error
        });
      }
    },
    // toLink
    toLink(path, query) {
      this.$router.push({
        path,
        query
      });
    },
    handlePagerSizeChange(v) {
      this.pager.limit = v;
      this.getTable();
    },
    handlePagerCurrentChange(v) {
      this.pager.page = v;
      this.getTable();
    }
  },
  created() {
    this.getTable();
    this.fetchSubjectOption();
  }
};
</script>